// 全局变量存储所有学生数据
let allStudents = [];

// 页面加载完成后初始化事件监听
document.addEventListener('DOMContentLoaded', function() {
    // 添加获取学生列表按钮的点击事件
    const fetchBtn = document.getElementById('fetchBtn');
    if (fetchBtn) {
        fetchBtn.addEventListener('click', function() {
            // 隐藏聊天机器人区域
            const chatbotContainer = document.querySelector('.chatbot-container');
            if (chatbotContainer) chatbotContainer.style.display = 'none';
            
            // 执行获取学生列表功能
            fetchStudents();
        });
    }
    
    // 添加搜索框的输入事件
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('input', filterStudents);
    }
    
    // 添加翻译按钮的点击事件
    const translateBtn = document.getElementById('translateBtn');
    if (translateBtn) {
        translateBtn.addEventListener('click', function() {
            // 隐藏学生列表相关功能区域
            const searchContainer = document.getElementById('search-container');
            const statsContainer = document.getElementById('statistics-container');
            const resultDiv = document.getElementById('result');
            
            if (searchContainer) searchContainer.style.display = 'none';
            if (statsContainer) statsContainer.style.display = 'none';
            if (resultDiv) {
                resultDiv.innerHTML = '<p>点击上方按钮获取学生信息</p>';
                resultDiv.className = 'result-area';
            }
            
            // 显示聊天机器人区域
            const chatbotContainer = document.querySelector('.chatbot-container');
            if (chatbotContainer) {
                chatbotContainer.style.display = 'block';
                // 移除滚动行为，保持页面当前位置
            }
        });
    }
});

/**
 * 从后端API获取学生数据
 */
async function fetchStudents() {
    const resultDiv = document.getElementById('result');
    const loadingDiv = document.getElementById('loading');
    const searchContainer = document.getElementById('search-container');
    const statsContainer = document.getElementById('statistics-container');
    
    // 显示加载状态
    if (resultDiv) {
        resultDiv.innerHTML = '';
        resultDiv.className = '';
    }
    if (loadingDiv) loadingDiv.style.display = 'block';
    if (searchContainer) searchContainer.style.display = 'none';
    if (statsContainer) statsContainer.style.display = 'none';
    
    try {
        // 通过Nginx代理访问后端服务
        // 根据配置，Nginx监听8080端口
        const response = await fetch('http://localhost:8080/students', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        
        const students = await response.json();
        allStudents = students;
        
        // 隐藏加载状态
        if (loadingDiv) loadingDiv.style.display = 'none';
        
        // 显示学生列表
        if (students && students.length > 0) {
            // 显示搜索框
            if (searchContainer) searchContainer.style.display = 'block';
            
            // 计算统计数据
            updateStatistics(students);
            if (statsContainer) statsContainer.style.display = 'grid';
            
            // 显示学生列表
            displayStudents(students);
        } else {
            if (resultDiv) {
                resultDiv.className = 'result-area empty';
                resultDiv.innerHTML = '<p>暂无学生数据</p>';
            }
        }
    } catch (error) {
        // 隐藏加载状态
        if (loadingDiv) loadingDiv.style.display = 'none';
        
        // 显示错误信息
        if (resultDiv) {
            resultDiv.innerHTML = `<div class="error"><span class="error-icon">⚠️</span>获取数据失败: ${error.message}</div>`;
        }
        console.error('获取学生数据时出错:', error);
    }
}

/**
 * 在页面上显示学生列表
 * @param {Array} students - 学生数据数组
 */
function displayStudents(students) {
    const resultDiv = document.getElementById('result');
    
    // 先清除现有内容并设置基本样式
    resultDiv.innerHTML = '';
    resultDiv.className = '';
    
    // 创建表格容器
    const tableContainer = document.createElement('div');
    tableContainer.className = 'table-container';
    
    // 创建表格
    const table = document.createElement('table');
    table.innerHTML = '<tr><th>ID</th><th>姓名</th><th>年龄</th><th>专业</th></tr>';
    
    // 添加学生行
    students.forEach((student, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${student.id}</td>
            <td>${student.name}</td>
            <td>${student.age}</td>
            <td>${student.major}</td>
        `;
        row.style.opacity = '0';
        row.style.transform = 'translateY(10px)';
        row.style.transition = `opacity ${0.15 * (index + 1)}s ease-out, transform ${0.15 * (index + 1)}s ease-out`;
        
        table.appendChild(row);
        
        // 使用setTimeout来触发动画，确保DOM已更新
        setTimeout(() => {
            row.style.opacity = '1';
            row.style.transform = 'translateY(0)';
        }, 50);
    });
    
    // 组装并添加到结果区域
    tableContainer.appendChild(table);
    resultDiv.appendChild(tableContainer);
    
    // 添加淡入动画类
    setTimeout(() => {
        resultDiv.className = 'fade-in';
    }, 10);
}

/**
 * 根据搜索词过滤学生数据
 */
function filterStudents() {
    const searchInput = document.getElementById('searchInput');
    const resultDiv = document.getElementById('result');
    
    if (!searchInput || !resultDiv) return;
    
    const searchTerm = searchInput.value.toLowerCase();
    
    if (!searchTerm.trim()) {
        displayStudents(allStudents);
        return;
    }
    
    const filteredStudents = allStudents.filter(student => 
        student.name.toLowerCase().includes(searchTerm) || 
        student.major.toLowerCase().includes(searchTerm)
    );
    
    if (filteredStudents.length > 0) {
        displayStudents(filteredStudents);
    } else {
        resultDiv.className = 'result-area empty';
        resultDiv.innerHTML = '<p>未找到匹配的学生数据</p>';
    }
}

/**
 * 更新统计数据
 * @param {Array} students - 学生数据数组
 */
function updateStatistics(students) {
    // 总人数
    document.getElementById('totalStudents').textContent = students.length;
    
    // 平均年龄
    if (students.length > 0) {
        const totalAge = students.reduce((sum, student) => sum + student.age, 0);
        const avgAge = (totalAge / students.length).toFixed(1);
        document.getElementById('avgAge').textContent = avgAge;
    }
    
    // 专业数量
    const majors = new Set(students.map(student => student.major));
    document.getElementById('uniqueMajors').textContent = majors.size;
}